package com.jerkin.dubbo.context;

import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;

import lombok.SneakyThrows;

import java.lang.reflect.Method;

/**
 * @version V1.0
 * @ClassName: DubboFilter
 * @Description:
 * @author: huhongzhi
 * @date: 2020/8/3 22:00
 */
@Activate(
        group = {"consumer", "provider"}, order = -2
)
public class DubboFilter implements Filter {

    @SneakyThrows
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

//        String key = invoker.getInterface().getName() + "#" + invocation.getMethodName();
//        ExceptionHandleRo exceptionHandleRo = InitExceptionHandleAnnotaions.getExceptionHandle(key);
//        Result result = null;
//        try {
            return invoker.invoke(invocation);
//        } catch (Exception e) {
//            if (isInvoke(e, exceptionHandleRo)) {
//                String[] referceMethod = exceptionHandleRo.getReferenceMethod().split("#");
//                String bean = referceMethod[0];
//                String method = referceMethod[1];
//                Method method1 = invoker.getInterface().getMethod(method, invocation.getParameterTypes());
//                method1.invoke(BeanHelper.getBean(bean), invocation.getArguments());
//            }
//        }
//        return result;
    }

    public Boolean isInvoke(Exception e, ExceptionHandleRo exceptionHandleRo) {
        for (Class<? extends Throwable> throwable : exceptionHandleRo.getExceptions()) {
            if (e instanceof Throwable) {
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }
}
